package edu.ubb.bibliospring.api.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.ubb.bibliospring.api.exception.BiblioSpringApiException;

import javax.ws.rs.NotAllowedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class ApiExceptionMapper implements ExceptionMapper<Exception>
{
    private final Logger logger = LoggerFactory.getLogger(ApiExceptionMapper.class);

    @Override
    public Response toResponse(final Exception ex)
    {
        if (ex instanceof BiblioSpringApiException)
        {
            return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
        }

        if (ex instanceof NotAllowedException)
        {
            return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
        }

        if (ex instanceof NotFoundException)
        {
            return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
        }

        logger.error("Converting Error to Api Response", ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal server error").build();
    }

}
